//
//  AddTaskViewController.m
//  OAProject
//
//  Created by yhj on 2017/3/8.
//  Copyright © 2017年 cdnunion. All rights reserved.
//  创建任务主界面

#import "AddTaskViewController.h"
#import "CommonTableViewCell.h"
#import "MemberTableViewCell.h"
#import "ProjectListViewController.h"
#import "TaskProcessViewController.h"
#import "RemarkTableViewCell.h"
#import "TaskSortViewController.h"
#import "LQPopUpView.h"
#import "AddTaskProcessViewController.h"
#import "MCAWSS3Client.h"
#import "NSString+SizeFile.h"
#import <Photos/Photos.h>
#import "MBProgressHUD+NH.h"


static NSString *RemarkTableViewCellIdentifier=@"RemarkTableViewCellIdentifier";
static NSString *MemberTableViewCellIdentifier=@"MemberTableViewCellIdentifier";
static NSString *CommonTableViewCellIdentifier=@"CommonTableViewCellIdentifier";
@interface AddTaskViewController ()<UITableViewDelegate,UITableViewDataSource,RemarkTableViewCellDelegate,CuiPickViewDelegate,UITextViewDelegate,ProjectListViewControllerDelegate,TaskSortViewControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,TZImagePickerControllerDelegate,UITextFieldDelegate,TaskProcessViewControllerDelegate>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)CuiPickerView *pickerView;

// 开始时间
@property(nonatomic,strong)NSString *startTimeStr;

@property(nonatomic,strong)UIView *taskInfoView;

// 优先级
@property(nonatomic,strong)NSString *priorityStr;
@property(nonatomic,strong)NSString *priorityID;

// 项目名称
@property(nonatomic,strong)NSString *projectName;

// 项目ID
@property(nonatomic,strong)NSString *projectID;

// 分类名称
@property(nonatomic,strong)NSMutableArray *sortNameArr;

@property(nonatomic,strong)NSString *sortName;


@property(nonatomic,strong)NSMutableArray *sortIDsArr;

// 分类ID
@property(nonatomic,strong)NSString *sortID;

// 任务流程名称
@property(nonatomic,strong)NSString *taskProgressName;

// 任务流程ID
@property(nonatomic,strong)NSString *taskProgressID;

// 任务名称
@property(nonatomic,strong)UITextField *nameTF;

// 任务目标
@property(nonatomic,strong)UITextView *taskGoalTV;

// 执行方法
@property(nonatomic,strong)UITextView *taskMethodTV;

// 任务ID
@property(nonatomic,strong)NSString *taskID;

@property(nonatomic,strong)NSMutableArray *fileArr;

@property(nonatomic,strong)NSMutableDictionary *dicKey;

@property(nonatomic,strong)NSMutableArray *uploadPhotoArr;

// 备注文字
@property(nonatomic,strong)NSString *remarkStr;

@property(nonatomic,assign)BOOL isChangeTime;

@property(nonatomic,strong)NSMutableArray *taskProgressArr;

@end

@implementation AddTaskViewController

-(void)currentTaskProgressArr:(NSMutableArray *)taskProgressArr
{
    self.taskProgressArr=taskProgressArr;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.taskProgressArr=[NSMutableArray array];


    _isChangeTime=NO;

    self.title=@"创建任务";

    self.dicKey=[NSMutableDictionary dictionary];

    self.uploadPhotoArr=[NSMutableArray array];

    // 获取任务taskID
    [self GetTaskIDData];

    _sortIDsArr=[NSMutableArray array];

    _sortNameArr=[NSMutableArray array];

    _fileArr=[NSMutableArray array];

    [self.view addSubview:self.tableView];

    [AppUI initNavigationItem:self.navigationItem andWithText:@"创  建" andTextColor:WhiteColor andIsRight:YES withBlock:^{

        // 创建任务
        [self publishTaskToService];

    }];
}

-(void)GetTaskIDData
{
    [API AddTaskSuccess:^(id res) {

        self.taskID=res[@"task_id"];

    } failure:^(NSInteger stateCode) {

    }];
}

-(void)publishTaskToService
{
    if (self.nameTF.text.length==0)
    {
      [self.view makeToast:@"请输入任务名称" duration:1 position:CSToastPositionCenter];
    }
    else if (self.taskGoalTV.text.length==0)
    {
     [self.view makeToast:@"请输入任务目标" duration:1 position:CSToastPositionCenter];
    }
    else if (self.taskMethodTV.text.length==0)
    {
    [self.view makeToast:@"请输入执行办法" duration:1 position:CSToastPositionCenter];
    }
    else if (self.projectID.length==0)
    {
     [self.view makeToast:@"请选择所属项目" duration:1 position:CSToastPositionCenter];
    }
    else if (self.sortIDsArr.count==0)
    {
     [self.view makeToast:@"请选择任务分类" duration:1 position:CSToastPositionCenter];
    }
    else if (self.taskProgressArr.count==0)
    {
       [self.view makeToast:@"请必须创建一个流程才能发布任务" duration:1 position:CSToastPositionCenter];
    }
    else if (self.priorityStr==nil)
    {
        [self.view makeToast:@"请选择优先级" duration:1 position:CSToastPositionCenter];
    }

//    else if (self.self.startTimeStr.length==0)
//    {
//      [self.view makeToast:@"请选择开始时间" duration:1 position:CSToastPositionCenter];
//    }
    else
    {
        if (self.nameTF.text.length>30)
        {
            [self.view makeToast:@"任务名称太长了" duration:1 position:CSToastPositionCenter];
        }
        else
        {
            [API PublicTaskWithTaskID:self.taskID projectID:self.projectID title:self.nameTF.text target_types:self.sortIDsArr priority:self.priorityID estimate_stime:(_isChangeTime==YES)?self.startTimeStr:[Util getCurrentTimes] target_desc:self.taskGoalTV.text exec_method:self.taskMethodTV.text memo:self.remarkStr attachments:self.dicKey success:^(id res) {

                if ([res[@"rt"] isEqual:@(1)])
                {
                    [self.view makeToast:@"任务发布成功" duration:1 position:CSToastPositionCenter];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                        [self.navigationController popViewControllerAnimated:NO];
                    });
                }
                else
                {
                    [self.view makeToast:res[@"error"] duration:1 position:CSToastPositionCenter];
                }

//                  self.navigationItem.rightBarButtonItem.enabled=NO;

            } failure:^(NSInteger stateCode) {
                
            }];
        }
    }

//    NSLog(@"sadhjshsdjh--");
//    self.navigationItem.rightBarButtonItem.enabled=NO;
//    self.navigationItem.rightBarButtonItem.tintColor=[UIColor redColor];
}

-(UIView *)taskInfoView
{
    if (!_taskInfoView) {
        _taskInfoView=[[UIView alloc]initWithFrame:CGRectMake(0,0,APPW,0)];
        _taskInfoView.backgroundColor=WhiteColor;
        setViewHeight_Add(_taskInfoView,kmargin);

        // 任务名称
        UILabel *taskNameLabel=[self.taskInfoView getLabelWithText:@"任务名称" font:Font_Number(16) textColor:DarkGreyColor textAlignment:NSTextAlignmentLeft lineBreakMode:NSLineBreakByCharWrapping numberOfLines:1];
        [self.taskInfoView addSubview:taskNameLabel];
        taskNameLabel.frame=CGRectMake(kmargin*2,_taskInfoView.frame.size.height,APPW/2,30);
        setViewHeight_Add(_taskInfoView,kmargin*3);

        _nameTF=[[UITextField alloc]initWithFrame:CGRectMake(kmargin*2,_taskInfoView.frame.size.height,APPW-kmargin*4,30)];
        _nameTF.placeholder=@"请输入任务名称";
        _nameTF.delegate=self;
        // 修改placeholder颜色
        [_nameTF setValue:LightGreyColor forKeyPath:@"_placeholderLabel.textColor"];
//        _nameTF.borderStyle=UITextBorderStyleRoundedRect;
        [self.taskInfoView addSubview:_nameTF];
        _nameTF.font=Font_Number(16);
        setViewHeight_Add(_taskInfoView,kmargin*5);


        UIView *lineView1=[[UIView alloc]initWithFrame:CGRectMake(0,self.taskInfoView.frame.size.height,APPW,1)];
        lineView1.backgroundColor=MAIN_BACK_COLOR;
        [self.taskInfoView addSubview:lineView1];


        // 任务目标
        UILabel *taskGoalLabel=[self.taskInfoView getLabelWithText:@"任务目标" font:Font_Number(16) textColor:DarkGreyColor textAlignment:NSTextAlignmentLeft lineBreakMode:NSLineBreakByCharWrapping numberOfLines:1];
        [self.taskInfoView addSubview:taskGoalLabel];
        taskGoalLabel.frame=CGRectMake(kmargin*2,_taskInfoView.frame.size.height+kmargin,APPW/2,30);
        setViewHeight_Add(_taskInfoView,kmargin*4);

        _taskGoalTV=[[UITextView alloc]initWithFrame:CGRectMake(kmargin,_taskInfoView.frame.size.height,APPW-kmargin*2,kmargin*6)];
        _taskGoalTV.delegate=self;
        _taskGoalTV.font=Font_Number(16);
        _taskGoalTV.placeholder=@"请输入任务目标";
        _taskGoalTV.textColor=DarkGreyColor;
//        ViewBorderRadius(_taskGoalTV,2,1,MAIN_BACK_COLOR);
        [self.taskInfoView addSubview:_taskGoalTV];
        setViewHeight_Add(_taskInfoView,kmargin*8);

        UIView *lineView2=[[UIView alloc]initWithFrame:CGRectMake(0,_taskInfoView.frame.size.height,APPW,1)];
        lineView2.backgroundColor=MAIN_BACK_COLOR;
        [self.taskInfoView addSubview:lineView2];


        // 执行办法
        UILabel *taskMethodLabel=[self.taskInfoView getLabelWithText:@"执行办法" font:Font_Number(16) textColor:DarkGreyColor textAlignment:NSTextAlignmentLeft lineBreakMode:NSLineBreakByCharWrapping numberOfLines:1];
        [self.taskInfoView addSubview:taskMethodLabel];
        taskMethodLabel.frame=CGRectMake(kmargin*2,_taskInfoView.frame.size.height+kmargin,APPW/2,30);
        setViewHeight_Add(_taskInfoView,kmargin*4);

        _taskMethodTV=[[UITextView alloc]initWithFrame:CGRectMake(kmargin,_taskInfoView.frame.size.height,APPW-kmargin*2,kmargin*6)];
        _taskMethodTV.delegate=self;
        _taskMethodTV.font=Font_Number(16);
        _taskMethodTV.placeholder=@"请输入执行办法";
        _taskMethodTV.textColor=DarkGreyColor;
//        ViewBorderRadius(_taskMethodTV,2,1,MAIN_BACK_COLOR);
        [self.taskInfoView addSubview:_taskMethodTV];
        setViewHeight_Add(_taskInfoView,kmargin*8);

        UIButton *fileBtn=[AppUI createButtonWithSupeView:self.taskInfoView andWithNormalImage:[UIImage imageNamed:@"addFile"] andWithSelectImage:[UIImage imageNamed:@"addFile"] andWithBtnAction:^{

            // 添加附件
            [self showSheetView];

        }];
        ViewBorderRadius(fileBtn,kmargin/2,.5,LightGreyColor);
        [self.taskInfoView addSubview:fileBtn];
        fileBtn.frame=CGRectMake(kmargin*2,_taskInfoView.frame.size.height,kmargin*4,kmargin*3);
        setViewHeight_Add(_taskInfoView,kmargin*4);

        UIView *lineView=[[UIView alloc]initWithFrame:CGRectMake(0,_taskInfoView.frame.size.height,APPW,kmargin)];
        lineView.backgroundColor=BGColor;
        [self.taskInfoView addSubview:lineView];
        setViewHeight_Add(_taskInfoView,kmargin);
        
    }
    return _taskInfoView;
}


// tableView
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0,0,APPW,APPH) style:UITableViewStylePlain];
        _tableView.dataSource=self;
        _tableView.delegate=self;
        _tableView.backgroundColor=MAIN_BACK_COLOR;
        _tableView.showsVerticalScrollIndicator=NO;
        _tableView.tableHeaderView=self.taskInfoView;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
        self.tableView.tableFooterView=[UIView new];

        [self.tableView registerClass:[CommonTableViewCell class] forCellReuseIdentifier:CommonTableViewCellIdentifier];
        [self.tableView registerClass:[MemberTableViewCell class] forCellReuseIdentifier:MemberTableViewCellIdentifier];
        [self.tableView registerClass:[RemarkTableViewCell class] forCellReuseIdentifier:RemarkTableViewCellIdentifier];
    }
    return _tableView;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 所属项目
     if (indexPath.row==0)
    {
        CommonTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CommonTableViewCellIdentifier];
        NSString *projectName;
        if (self.projectName==nil)
        {
            projectName=@"请选择所属项目";
        }
        else
        {
            projectName=self.projectName;
        }
        [cell setCellInfoWithHeaderImage:@"" withTitle:@"所属项目" withSubTitle:projectName withArrow:YES];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    // 任务分类
    else  if (indexPath.row==1)
    {
        CommonTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CommonTableViewCellIdentifier];
        NSString *sortName;
        if (self.sortName==nil)
        {
            sortName=@"请选择任务分类";
        }
        else
        {
            sortName=self.sortName;
        }
        [cell setCellInfoWithHeaderImage:@"" withTitle:@"任务分类" withSubTitle:sortName withArrow:YES];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    // 开始时间
    else  if (indexPath.row==2)
    {
        NSString *timeStr;
        if (!self.isChangeTime)
        {
            // [NSDate date]
            timeStr=[Util getCurrentTimes];
            NSLog(@"sdhghdhgdf9900---%@",timeStr);

            NSLog(@"sjhjshds445445---%@",[Util getCurrentTimes]);

        }
        else
        {
            timeStr=self.startTimeStr;
        }
        CommonTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CommonTableViewCellIdentifier];
        [cell setCellInfoWithHeaderImage:@"" withTitle:@"开始时间" withSubTitle:timeStr withArrow:YES];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    // 任务流程
    else  if (indexPath.row==3)
    {
        CommonTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CommonTableViewCellIdentifier];
        [cell setCellInfoWithHeaderImage:@"" withTitle:@"任务流程" withSubTitle:@"" withArrow:YES];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    // 优先级
    else  if (indexPath.row==4)
    {
        NSString *priorityStr;
        if (self.priorityStr==nil)
        {
          priorityStr=@"请选择优先级";
        }
        else
        {
            priorityStr=self.priorityStr;
        }
        CommonTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CommonTableViewCellIdentifier];
        [cell setCellInfoWithHeaderImage:@"" withTitle:@"优  先  级" withSubTitle:priorityStr withArrow:YES];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
    else
    {
        RemarkTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:RemarkTableViewCellIdentifier];
        cell.delegate=self;
        cell.remarkTextView.delegate=self;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];

     if (indexPath.row==0)
    {
        // 跳转到 项目列表 界面
        ProjectListViewController *vc=[ProjectListViewController new];
        vc.delegate=self;
        [self.navigationController pushViewController:vc animated:NO];
    }
     else if (indexPath.row==1)
    {
        // 跳转到 分类列表 界面
        TaskSortViewController *vc=[TaskSortViewController new];
        vc.delegate=self;
        [self.navigationController pushViewController:vc animated:NO];
    }
    else if (indexPath.row==2)
    {
         // 开始时间
         [self GetStartTime];
    }
    else if (indexPath.row==3)
    {
//        // 在创建流程之前必须选择开始时间且必须大于当前时间
//        if (self.startTimeStr==nil)
//        {
//            [self.view makeToast:@"请选择开始时间" duration:1 position:CSToastPositionCenter];
//            return;
//        }
//        else
        {
            [self GetTaskProcessListData];
        }
    }
    else if (indexPath.row==4)
    {
        // 获取优先级数据
        [self GetPriorityListData];
    }
    else
    {
        RemarkTableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
        [cell.remarkTextView becomeFirstResponder];
    }
}

// 去流程列表界面
-(void)GetTaskProcessListData
{
    // 有流程列表数据
    TaskProcessViewController *vc=[TaskProcessViewController new];
    vc.taskID=self.taskID;
    NSString *timeStr;
    if (!self.isChangeTime)
    {
        timeStr=[Util getCurrentTimes];
    }
    else
    {
        timeStr=self.startTimeStr;
    }
//    vc.startTimeStr=self.startTimeStr;
    vc.startTimeStr=timeStr;
    vc.delegate=self;
    [self.navigationController pushViewController:vc animated:NO];


//    // 获取流程列表
//    [API GetTaskProgressListWithTaskID:self.taskID success:^(id res) {
//
//        if ([res[@"rt"] isEqual:@(1)])
//        {
//            if ([res[@"rows"]count]>0)
//            {
//               // 有流程列表数据
//                TaskProcessViewController *vc=[TaskProcessViewController new];
//                vc.taskID=self.taskID;
//                vc.taskProgressListArr=res[@"rows"];
//                [self.navigationController pushViewController:vc animated:NO];
//            }
//            else
//            {
//                // 无流程列表数据
//                AddTaskProcessViewController *vc=[AddTaskProcessViewController new];
//                vc.taskID=self.taskID;
//                vc.isFirst=YES;
//                vc.startTimeStr=self.startTimeStr;
//                [self.navigationController pushViewController:vc animated:NO];
//            }
//        }
//        else
//        {
//            [self.view makeToast:res[@"error"] duration:1 position:CSToastPositionCenter];
//        }
//
//    } failure:^(NSInteger stateCode) {
//    }];

}

// delegate
-(void)selectProjectName:(NSString *)projectName projectID:(NSString *)projectID
{
    self.projectName=projectName;
    self.projectID=projectID;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

// delegate
-(void)selectTaskSortName:(NSString *)taskSortName taskSortID:(NSString *)taskSortID
{
    [self.sortIDsArr addObject:taskSortID];

    self.sortID=taskSortID;

    self.sortName=taskSortName;

    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

}


-(void)selectTaskSortNameArr:(NSMutableArray *)taskSortNameArr taskSortIDs:(NSMutableArray *)taskSortIDs
{
    self.sortNameArr=taskSortNameArr;
    self.sortIDsArr=taskSortIDs;

    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}


// delegate
-(void)selectTaskProcessName:(NSString *)taskProcessName taskProcessID:(NSString *)taskProcessID
{
    self.taskProgressName=taskProcessName;
    self.taskProgressID=taskProcessID;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}

// 开始时间
-(void)GetStartTime
{
    CuiPickerView *pickerView=[CuiPickerView new];
    pickerView.frame=CGRectMake(0,APPH,APPW,320);
    pickerView.delegate=self;
    pickerView.backgroundColor=BGColor;
    pickerView.curDate=[NSDate date];
    _pickerView=pickerView;
    [self.view addSubview:pickerView];
    [_pickerView showInView:self.view];
}


// delegate
-(void)didFinishPickView:(NSString *)date
{
    self.startTimeStr=date;
    _isChangeTime=YES;

    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}



-(void)hiddenPickerView
{

}

// 获取优先级数据
-(void)GetPriorityListData
{
    [API GetPriorityListSuccess:^(id res) {

        NSLog(@"sdjkjdfjkdfjk00---%@",res);



        NSDictionary *dic=res[@"rows"];

        LQPopUpView *popUpView = [[LQPopUpView alloc] initWithTitle:@"选择优先级" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[dic[@"1"],dic[@"3"]] actionWithIndex:^(NSInteger index) {

            // 普通
            if (index==1)
            {
               self.priorityStr=@"普通";

               self.priorityID=@"1";
            }
//            // 高
//            else if (index==2)
//            {
//               self.priorityStr=@"高";
//               self.priorityID=@"2";
//            }
            // 紧急
            else if (index==2)
            {
               self.priorityStr=@"紧急";
               self.priorityID=@"3";
            }
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:4 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }];

        [popUpView showInView:self.view preferredStyle:LQPopUpViewStyleAlert];

    } failure:^(NSInteger stateCode) {

    }];
}

// delegate
-(void)GetTextViewHeightByInputRemarkStr:(NSString *)remarkStr textViewHeight:(CGFloat)textViewHeight cell:(RemarkTableViewCell *)cell
{
    self.remarkStr=remarkStr;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kmargin*5;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footView=[UIView new];
    return footView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return kmargin*2;
}

// 间隙置边
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{

    if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


-(void)showSheetView
{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *setAlert=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self callCameraOrPhotoWithType:UIImagePickerControllerSourceTypeCamera];

    }];
    UIAlertAction *PhoneAlert=[UIAlertAction actionWithTitle:@"从手机选择" style:
                   UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:20 delegate:self];

       // 在这里设置imagePickerVc的外观
       imagePickerVc.navigationBar.barTintColor=MainColor;
       imagePickerVc.oKButtonTitleColorDisabled=MainColor;
       imagePickerVc.oKButtonTitleColorNormal=[UIColor greenColor];
       // 设置是否可以选择视频/原图
       imagePickerVc.allowPickingVideo=YES;
       imagePickerVc.allowPickingOriginalPhoto=YES;
       imagePickerVc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
       [self presentViewController:imagePickerVc animated:NO completion:nil];

   }];
    UIAlertAction *hidAlert = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:setAlert];
    [alert addAction:PhoneAlert];
    [alert addAction:hidAlert];
    
    [self presentViewController:alert animated:NO completion:^{
        
    }];
}

-(void)callCameraOrPhotoWithType:(UIImagePickerControllerSourceType)sourceType{
    BOOL isCamera = YES;
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {//判断是否有相机
        isCamera = [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera];
    }
    if (isCamera) {
        UIImagePickerController *imagePicker=[[UIImagePickerController alloc] init];
        imagePicker.delegate=self;
        imagePicker.allowsEditing=NO;//为NO，则不会出现系统的编辑界面
        imagePicker.sourceType = sourceType;
        [self presentViewController:imagePicker animated:YES completion:^(){
            if ([[[UIDevice currentDevice] systemVersion]floatValue]>=7.0) {
                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
            }
        }];
    }
    else
    {
        UIAlertView *alert=[UIAlertView alertViewWithTitle:@"该设备不支持拍照" message:nil cancelButtonTitle:nil didDismissBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        } otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset
{
    if ([[[[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."] objectAtIndex:0] intValue] >= 8){
        PHAsset* phAsset = (PHAsset*)asset;
        if (phAsset.mediaType == PHAssetMediaTypeVideo) {
            PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
            options.version = PHImageRequestOptionsVersionCurrent;
            options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;

            PHImageManager *manager = [PHImageManager defaultManager];
            [manager requestAVAssetForVideo:phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
                AVURLAsset *urlAsset = (AVURLAsset *)asset;
                NSURL *url = urlAsset.URL;
                [self uploadMov:url andMovDuration:phAsset.duration andSize:[NSData dataWithContentsOfURL:url].length];
            }];
        }
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingGifImage:(UIImage *)animatedImage sourceAssets:(id)asset
{
    NSLog(@"%@",animatedImage);
}

- (void)uploadMov:(NSURL*)movUrl andMovDuration:(NSTimeInterval)duration andSize:(float)size
{
    NSData *data=[NSData dataWithContentsOfURL:movUrl];
    NSString *key=movUrl.lastPathComponent;

    MCAWSS3Client *client=[[MCAWSS3Client alloc] init];
    [client setAccessKey:[Util getUserDefaultObjectForKey:@"access_key"]];
    [client setSecretKey:[Util getUserDefaultObjectForKey:@"access_secret"]];
    [client setSessionToken:[Util getUserDefaultObjectForKey:@"TToken"]];
    [client setBucket:[Util getUserDefaultObjectForKey:@"bucket"]];

    [client putObjectWithData:data
              key:key
         mimeType:@"video/x-sgi-movie"
         progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {

             if (totalBytesWritten < totalBytesExpectedToWrite)
             {
                 [SVProgressHUD showWithStatus:@"上传中"];
             }
             else
             {
                 [SVProgressHUD dismiss];

                [self.view makeToast:@"上传成功" duration:1 position:CSToastPositionCenter];
             }
         } success:^(AFHTTPRequestOperation *operation, id responseObject) {

             NSDictionary *moveDic=@{
                                      @"name":key,
                                      @"url":[NSString stringWithFormat:@"%@%@",FilePathBaseUrl,key],
                                      @"type":@"mov",
                                      @"size":[NSString stringWithFormat:@"%.f",size],
                                      @"duration":[NSString stringWithFormat:@"%.f",duration]
                                    };
            [self.dicKey setObject:moveDic forKey:key];

         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

         }];
}

#pragma mark - TZImagePickerController Delegate
// 处理从相册单选或多选的照片
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    [self uploadPhotos:photos];
}

//相册或则相机选择上传的实现
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)aImage editingInfo:(NSDictionary *)editingInfo{

    NSArray *photos = [[NSArray alloc]initWithObjects:aImage,nil];
    [picker dismissViewControllerAnimated:YES completion:^{
            [self uploadPhotos:photos];
    }];

}

-(void)uploadPhotos:(NSArray *)photoArr
{
    for (int i=0;i<photoArr.count;i++)
    {
       UIImage *uploadImage=photoArr[i];
        uploadImage=[Util scaleToSize:uploadImage size:CGSizeMake(180,uploadImage.size.height*(180.0/MAX(uploadImage.size.width,180)))];
        // 图片转向处理
        uploadImage =[uploadImage fixOrientation];

        // 获取当前时间
        NSDate *date=[NSDate date];
        NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyyMMddHHmmssss"];

        NSData *imageData=UIImageJPEGRepresentation(uploadImage,0.9f);
        NSString *uniquePath=[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%d.png",[formatter stringFromDate:date],i]];
        [imageData writeToFile:uniquePath atomically:NO];
        NSData *data=[NSData dataWithContentsOfFile:uniquePath];


        NSString *key=[NSURL fileURLWithPath:uniquePath].lastPathComponent;

        // 配置
        MCAWSS3Client *client=[MCAWSS3Client new];
        [client setAccessKey:[Util getUserDefaultObjectForKey:@"access_key"]];
        [client setSecretKey:[Util getUserDefaultObjectForKey:@"access_secret"]];
        [client setSessionToken:[Util getUserDefaultObjectForKey:@"TToken"]];
        [client setBucket:[Util getUserDefaultObjectForKey:@"bucket"]];

        NSDictionary *dic=@{
                            @"name":key,
                            @"url":[NSString stringWithFormat:@"%@%@",FilePathBaseUrl,key],
                            @"type":@"png",
                            @"size":[NSString stringWithFormat:@"%llu",uniquePath.fileSize],
                            };

        [client putObjectWithData:data
              key:key
         mimeType:@"image/png"
       permission:MCAWSS3ObjectPermissionPublicReadWrite
          success:^(AFHTTPRequestOperation *operation,id responseObject) {

              if (i == photoArr.count-1)
              {
                 [self.view makeToast:@"上传成功" duration:1 position:CSToastPositionCenter];
              }
              [self.dicKey setObject:dic forKey:key];

          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              
          }];
    }
}


// 点击return键时候键盘下去
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];

    return YES;
}

@end
